package com.palm.hubo2o.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.palm.hubo2o.BaseActivity;
import com.palm.hubo2o.R;
import com.palm.hubo2o.adapter.BetAdapter;
import com.palm.hubo2o.model.Bet;
import com.palm.hubo2o.model.BetSMS;
import com.palm.hubo2o.model.Issue;
import com.palm.hubo2o.network.PalmCallBack;
import com.palm.hubo2o.network.PalmRetrofit;
import com.palm.hubo2o.network.PalmSession;
import com.palm.hubo2o.network.Request;
import com.palm.hubo2o.util.EnumCode;
import com.palm.hubo2o.util.IssueCenter;
import com.palm.hubo2o.view.BetItemDecoration;
import com.palm.hubo2o.view.ProgressDialogCompat;
import com.palm.palmutils.LayoutUtils;
import com.palm.palmutils.ResourcesUtils;
import com.palm.palmutils.TimeUtils;
import com.palm.palmutils.widget.EasyRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;


/**
 * Created by dest1 on 2015/10/8.
 */
public class BetActivity extends BaseActivity implements View.OnLayoutChangeListener {
    @Bind(R.id.recycler_view)
    EasyRecyclerView mRecyclerView;
    @Bind(R.id.txt_lottery_info)
    TextView lotteryInfoTv;
    @Bind(R.id.edit_multiple_bottom)
    EditText multipleEdit;
    @Bind(R.id.hand_bet)
    TextView hand;
    @Bind(R.id.random_bet)
    TextView random;
    @Bind(R.id.layout_bottom)
    ViewGroup groupBottom;
    @Bind(R.id.btn_lottery_submit)
    Button submit;
    @Bind(R.id.countdown_bet)
    TextView countdownBet;
    private IssueCenter mIssueCenter;
    private BetAdapter mAdapter;
    private AlertDialog tipDialog;
    private ProgressDialogCompat dialog;
    private ArrayList<Bet> bets;//得到总的order
    private EnumCode.gameId gameId;//游戏玩法
    private long allNote;//总注数


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gameId = (EnumCode.gameId) getIntent().getSerializableExtra("gameId");
        setTheme(gameId == EnumCode.gameId.HBP3 ? R.style.AppTheme_K3 : R.style.AppTheme_Common);
        setContentView(R.layout.activity_bet);
        ButterKnife.bind(this);
        groupBottom.addOnLayoutChangeListener(this);
        submit.setText(R.string.action_send_sms);
        mIssueCenter = IssueCenter.open();
        if (mIssueCenter.switchIssue(gameId) == null) {
            mIssueCenter.startLoadCurrent(gameId);
            countdownBet.setText("当前暂无彩期");
        } else {
            Issue i = mIssueCenter.switchIssue(gameId);
            countdownBet.setText(TimeUtils.formatTime("HH:mm 截止投注", i.endTime));
        }
        setTitle(String.format("%s订单列表", gameId));
        mAdapter = new BetAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        ItemTouchHelper helper = new ItemTouchHelper(mCallback);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new BetItemDecoration(this, Color.rgb(198, 198, 198), ResourcesUtils.getAttrColor(this, R.attr.lotteryBackgroundColor)));
        int padding = LayoutUtils.dp2pix(this, 12);
        mRecyclerView.setPadding(padding, padding, padding, padding);
        mRecyclerView.setClipToPadding(false);
        helper.attachToRecyclerView(mRecyclerView);
        initBet(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initBet(intent);
    }

    @OnClick(R.id.hand_bet)
    public void hand() {
        Intent intent = null;
        //手选
        switch (gameId) {
            case SSQ:
                intent = new Intent(this, SSQLotteryActivity.class);
                break;
            case D3:
                intent = new Intent(this, D3LotteryActivity.class);
                break;
            case QLC:
                intent = new Intent(this, QLCLotteryActivity.class);
                break;
            case HBP3:
                intent = new Intent(this, K3LotteryActivity.class);
                break;
            default:
                break;

        }
        if (mAdapter.getBets().size() != 0) {
            intent.putExtra(EnumCode.PlayType.class.getName(), mAdapter.getBets().get(0).getPlayType());
        }
        startActivity(intent);

    }


    @OnClick(R.id.random_bet)
    public void random() {
//        Bet bet;
//        bet = BallUtils.getMachineBall(gameId);
//        if (bet != null) {
//            bet.setMultiple(Integer.parseInt(multipleEdit.getText().toString()));
//            mAdapter.addOrder(bet);
//            upOrderInfo();
//        }
    }


    @OnClick(R.id.btn_lottery_submit)
    public void submit() {

        /***
         * 验证用户是否登录
         * **/
        if (!PalmSession.isLogin()) {
            PalmSession.login(this);
            return;
        }

        /**
         * 验证期次是否变化
         * **/
        Issue issue = mIssueCenter.switchIssue(gameId);
        if (issue == null || issue.issueNo < 0) {
            Toast.makeText(this, "当前暂无彩期", Toast.LENGTH_SHORT).show();
            return;
        }

        final Bet bet = mergeBets(mAdapter.getBets());
        bet.setIssueNo(issue.issueNo);
        bet.setMultiple(Integer.valueOf(multipleEdit.getText().toString()));
        bet.setSeriesNo(1);//暂无追号
        bet.setTotalMoney(bet.getWagerCount() * bet.getMultiple() * 2);

        PalmRetrofit.getInstance().getApi().lotteryBet(new Request<>(bet)).enqueue(new PalmCallBack<BetSMS>(this) {
            @Override
            public void succeed(BetSMS betSMS) {
                Uri uri = Uri.parse("smsto:" + betSMS.getSmsCode());
                Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
                sendIntent.putExtra("sms_body", betSMS.getSmsContent());
                startActivity(sendIntent);
            }

            @Override
            public void failed(String message) {
                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @OnClick(R.id.btn_lottery_clean)
    public void resetOrders() {
        mAdapter.cleanUp();
        upOrderInfo();
    }

    /**
     * 监听软键盘
     */
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom == 0 || oldBottom == bottom)
            return;
        int viewHeight = v.getHeight();
        if (bottom - oldBottom < viewHeight) {//软件盘弹出
            //切换布局
        } else {//软键盘隐藏
            if (multipleEdit.hasFocus()) multipleEdit.clearFocus();
        }
    }

    @OnTextChanged(R.id.edit_multiple_bottom)
    public void changeMultiple() {
        String content = multipleEdit.getText().toString();
        if (TextUtils.isEmpty(content)) {
            multipleEdit.setText("1");
            multipleEdit.selectAll();
            return;
        } else if (0 == Integer.parseInt(content)) {
            multipleEdit.setText("1");
            Toast.makeText(this, "最小选择1倍", Toast.LENGTH_SHORT).show();
            return;
        } else if (50 < Integer.parseInt(content)) {
            multipleEdit.setText("50");
            Toast.makeText(this, "最大选择50倍", Toast.LENGTH_SHORT).show();
            return;
        }
        upOrderInfo();
    }

    private Bet mergeBets(List<Bet> bets) {
        if (bets == null || bets.size() == 0)
            return null;
        Bet fin = new Bet(bets.get(0).getGameId());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bets.size(); i++) {
            Bet bet = bets.get(i);
            fin.setWagerCount(fin.getWagerCount() + bet.getWagerCount());
            sb.append(bet.getPlayType().getTypeCode());
            for (int x = 0; x < bet.getReds().size(); x++) {
                if (x == 0)
                    sb.append(":");
                sb.append(bet.getReds().get(x));
                if (x != bet.getReds().size() - 1)
                    sb.append(bet.getSign());
            }
            for (int x = 0; x < bet.getTuos().size(); x++) {
                if (x == 0)
                    sb.append(":");
                sb.append(bet.getTuos().get(x));
                if (x != bet.getTuos().size() - 1)
                    sb.append(bet.getSign());
            }
            for (int x = 0; x < bet.getBlues().size(); x++) {
                if (x == 0)
                    sb.append(":");
                sb.append(bet.getBlues().get(x));
                if (x != bet.getBlues().size() - 1)
                    sb.append(bet.getSign());
            }
            if (i != bets.size() - 1)
                sb.append("|");
        }
        fin.setWager(sb.toString());
        return fin;
    }


    private void initBet(Intent intent) {
        Bet bet = intent.getParcelableExtra(Bet.TAG);
        mAdapter.addOrder(bet);
        //初始化订单
        upOrderInfo();
    }

    /***
     * 得到订单总数 更新订单金额
     **/
    private void upOrderInfo() {
        bets = mAdapter.getBets();
        allNote = 0;
        for (int i = 0; i < bets.size(); i++) {
            gameId = bets.get(i).getGameId();
            allNote += bets.get(i).getWagerCount();
        }

        if (Integer.parseInt(multipleEdit.getText().toString()) > 1) {

            int multipleNun = Integer.parseInt(multipleEdit.getText().toString());
            lotteryInfoTv.setText(String.format(Locale.getDefault(), "共%d注，%d倍，%d元", allNote, multipleNun, multipleNun * allNote * 2));
        } else {
            lotteryInfoTv.setText(String.format(Locale.getDefault(), "共%d注，%d元", allNote, allNote * 2));
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        showTipDialog();
    }

    private void showTipDialog() {
        if (tipDialog == null) {
            tipDialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.title_cancel_bet)
                    .setMessage(R.string.tips_confirm_bet)
                    .setNegativeButton(R.string.action_negative, null)
                    .setPositiveButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(BetActivity.this, MainActivity.class));
                        }
                    }).create();
        }
        tipDialog.show();
    }

    private final ItemTouchHelper.SimpleCallback mCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            mAdapter.getBets().remove(position);
            mAdapter.notifyItemRemoved(position);
            upOrderInfo();
        }
    };
}




